package cn.funnymap.lgis.tools.vector.parser;

import cn.funnymap.lgis.tools.exception.ShpParserRuntimeException;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.geojson.feature.FeatureJSON;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Shapefile-GeoJSON解析器
 *
 * @author jiaoxn
 */
public class Shp2GeojsonParser extends ShpParser<List<GeojsonContent>> {
    public Shp2GeojsonParser(ShpParseParameter parseParameter) {
        super(parseParameter);
    }

    @Override
    List<GeojsonContent> parseShapefile() {
        List<GeojsonContent> geojsonContentList = new ArrayList<>();
        try {
            for (Path shpFilePath : this.processorParameter.getShpFilePathList()) {
                SimpleFeatureCollection simpleFeatureCollection = this.readAndTransform(shpFilePath);
                String geojson = this.simpleFeatureCollection2Json(simpleFeatureCollection);
                List<ShpAttributeField> shpAttributeFieldList = this.readAttributeField(shpFilePath);

                geojsonContentList.add(new GeojsonContent(geojson, shpAttributeFieldList));
            }

            return geojsonContentList;
        } catch (IOException ioException) {
            throw new ShpParserRuntimeException("Shapefile文件解析失败，" + ioException.getCause());
        } finally {
            this.deleteRelatedFile();
        }
    }
    private String simpleFeatureCollection2Json(SimpleFeatureCollection simpleFeatureCollection) throws IOException {
        StringWriter stringWriter = new StringWriter();
        FeatureJSON featureJson = new FeatureJSON();
        featureJson.writeFeatureCollection(simpleFeatureCollection, stringWriter);
        return stringWriter.toString();
    }
}
